<?php

require("../requests/library/Requests.php");
require("../simple_html_dom.php");
Requests::register_autoloader();

class Server
{
    private $serv;

    public function __construct() 
    {
        $this->serv = new swoole_server("0.0.0.0", 9501);

        $this->serv->set(array(
            'worker_num' => 8,
            'daemonize' => false,
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'debug_mode'=> 1,
            'task_worker_num' => 25
        ));

        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Close', array($this, 'onClose'));
        
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }
    public function onStart( $serv ) 
    {
        echo "Start\n";
    }

    public function onConnect( $serv, $fd, $from_id ) 
    {
        echo "Client {$fd} connect\n";
    }

    public function onReceive( $serv, $fd, $from_id, $data ) 
    {
        $serv->task( $data  );//默认随机分发给task任务
    }

    public function onClose( $serv, $fd, $from_id ) 
    {
        echo "Client {$fd} close connection\n";
    }

    public function onTask($serv,$task_id,$from_id, $data) 
    {
		//具体处理task任务
        
		//根据路径存放文件夹
		$dirinfo = pathinfo($data);
		$dir = date('m') . '/' . date('d')  .'/'. $dirinfo['basename'];
		$root = '/home/www/php/data/';
		$absolute_dir = $root . $dir;

		if ( !is_dir( $absolute_dir  ) )
		{
			mkdir($absolute_dir, 0777, true);
		}

      	$urlbody = Requests::get($data,[], ['connect_timeout' => 100, 'timeout' => 100])->body;
		$urlhtml = str_get_html($urlbody);
		$imgs = $urlhtml->find('.topic-figure img');
    	
		foreach( $imgs as $img )
		{
			$img_info = pathinfo($img->src);
			$img_no = $img_info['basename'];
			file_put_contents( $absolute_dir . '/' . $img_no . '.jpg', file_get_contents($img->src) );
		}

		return $data;
    }

    public function onFinish($serv,$task_id, $data) 
    {
    	echo $data . ' download success';
    }
}
$server = new Server();
